/*
 * Copyright (C) 2009 Leandro de Oliveira Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.japa;

import java.util.*;

import org.springframework.dao.*;

import com.google.code.japa.engine.*;
import com.google.code.japa.util.*;
import com.google.code.liquidform.*;

/**
 * Enables easy execution of customized queries against the JPA repository.
 * 
 * @author Leandro Aparecido
 * @since 1.0
 * @see com.google.code.liquidform.LiquidForm
 * @see com.google.code.japa.engine.JapaEngine#executeQuery(String, Object...)
 */
public abstract class Repository {

	/**
	 * Query the repository using a custom LIQUidFORM clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param clause LIQUidFORM clause.
	 * @param params Positional parameters for the JPA query.
	 * @return List of entities matching the JPA query clause.
	 */
	public static <S> List<S> query(SubQuery<S> clause, Object... params) {
		return query(clause.toString(), params);
	}

	/**
	 * Query the repository using a custom LIQUidFORM clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param clause LIQUidFORM clause.
	 * @param params Positional parameters for the JPA query.
	 * @return List of entities matching the JPA query clause.
	 */
	public static <S> List<S> query(SelectClause<S> clause, Object... params) {
		return query(clause.toString(), params);
	}

	/**
	 * Query the repository using a custom LIQUidFORM clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param clause LIQUidFORM clause.
	 * @param params Positional parameters for the JPA query.
	 * @return List of entities matching the JPA query clause.
	 */
	public static <S> List<S> query(OrderByClause clause, Object... params) {
		return query(clause.toString(), params);
	}

	/**
	 * Query the repository using a custom LIQUidFORM clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param clause LIQUidFORM clause.
	 * @param params Positional parameters for the JPA query.
	 * @return Single entity matching the JPA query clause or
	 * {@link IncorrectResultSizeDataAccessException} if resulting list is empty or
	 * has more than a single element.
	 */
	@SuppressWarnings("unchecked")
	public static <S> S queryForObject(SubQuery<S> clause, Object... params) {
		return (S) queryForObject(clause.toString(), params);
	}

	/**
	 * Query the repository using a custom LIQUidFORM clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param <E> Exception type to be thrown if the result list does not have
	 * exactly one element.
	 * @param clause LIQUidFORM clause.
	 * @param exception Type of the exception to be thrown if the resulting list is
	 * empty or has more than a single element.
	 * @param params Positional parameters for the JPA query.
	 * @return Single entity matching the JPA query clause or
	 * an instance of the specified exception if resulting list is empty or
	 * has more than a single element.
	 */
	@SuppressWarnings("unchecked")
	public static <S, E extends Throwable> S queryForObject(SubQuery<S> clause, Class<E> exception, Object... params) throws E {
		return (S) queryForObject(clause.toString(), exception, params);
	}

	/**
	 * Query the repository using a custom LIQUidFORM clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param clause LIQUidFORM clause.
	 * @param params Positional parameters for the JPA query.
	 * @return Single entity matching the JPA query clause or
	 * {@link IncorrectResultSizeDataAccessException} if resulting list is empty or
	 * has more than a single element.
	 */
	@SuppressWarnings("unchecked")
	public static <S> S queryForObject(SelectClause<S> clause, Object... params) {
		return (S) queryForObject(clause.toString(), params);
	}

	/**
	 * Query the repository using a custom LIQUidFORM clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param <E> Exception type to be thrown if the result list does not have
	 * exactly one element.
	 * @param clause LIQUidFORM clause.
	 * @param exception Type of the exception to be thrown if the resulting list is
	 * empty or has more than a single element.
	 * @param params Positional parameters for the JPA query.
	 * @return Single entity matching the JPA query clause or
	 * an instance of the specified exception if resulting list is empty or
	 * has more than a single element.
	 */
	@SuppressWarnings("unchecked")
	public static <S, E extends Throwable> S queryForObject(SelectClause<S> clause, Class<E> exception, Object... params) throws E {
		return (S) queryForObject(clause.toString(), exception, params);
	}

	/**
	 * Query the repository using a custom LIQUidFORM clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param clause LIQUidFORM clause.
	 * @param params Positional parameters for the JPA query.
	 * @return Single entity matching the JPA query clause or
	 * {@link IncorrectResultSizeDataAccessException} if resulting list is empty or
	 * has more than a single element.
	 */
	@SuppressWarnings("unchecked")
	public static <S> S queryForObject(OrderByClause clause, Object... params) {
		return (S) queryForObject(clause.toString(), params);
	}

	/**
	 * Query the repository using a custom LIQUidFORM clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param <E> Exception type to be thrown if the result list does not have
	 * exactly one element.
	 * @param clause LIQUidFORM clause.
	 * @param exception Type of the exception to be thrown if the resulting list is
	 * empty or has more than a single element.
	 * @param params Positional parameters for the JPA query.
	 * @return Single entity matching the JPA query clause or
	 * an instance of the specified exception if resulting list is empty or
	 * has more than a single element.
	 */
	@SuppressWarnings("unchecked")
	public static <S, E extends Throwable> S queryForObject(OrderByClause clause, Class<E> exception, Object... params) throws E {
		return (S) queryForObject(clause.toString(), exception, params);
	}

	/**
	 * Query the repository using a custom JPA clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param clause String clause.
	 * @param params Positional parameters for the JPA query.
	 * @return Single entity matching the JPA query clause or
	 * {@link IncorrectResultSizeDataAccessException} if resulting list is empty or
	 * has more than a single element.
	 */
	public static <S> S queryForObject(String clause, Object... params) {
		List<S> list = query(clause, params);
		if (list.isEmpty() || list.size() > 1) {
			throw new IncorrectResultSizeDataAccessException(1, list.size());
		}
		return list.get(0);
	}

	/**
	 * Query the repository using a custom JPA clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param clause String clause.
	 * @param exception Type of the exception to be thrown if the resulting list is
	 * empty or has more than a single element.
	 * @param params Positional parameters for the JPA query.
	 * @return Single entity matching the JPA query clause or
	 * an instance of the specified exception if resulting list is empty or
	 * has more than a single element.
	 */
	public static <S, E extends Throwable> S queryForObject(String clause, Class<E> exception, Object... params) throws E {
		List<S> list = query(clause, params);
		if (list.isEmpty() || list.size() > 1) {
			try {
				throw exception.newInstance();
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			} catch (InstantiationException e) {
				throw new RuntimeException(e);
			}
		}
		return list.get(0);
	}

	/**
	 * Query the repository using a custom JPA clause.
	 * 
	 * @param <S> Entity type returned by the query.
	 * @param clause LIQUidFORM clause.
	 * @param params Positional parameters for the JPA query.
	 * @return List of entities matching the JPA query clause.
	 */
	public static <S> List<S> query(String clause, Object... params) {
		return getJapaEngine().executeQuery(clause, params);
	}
	
	/**
	 * Retrieves an entity instance using its id.
	 * 
	 * @param <T> Entity type.
	 * @param entityClass Entity class.
	 * @param id Id of the entity to retrieve.
	 * @return Entity instance retrieved or null if not found.
	 */
	public static <T> T byId(Class<T> entityClass, Object id) {
		return getJapaEngine().findById(entityClass, id);
	}

	/**
	 * Retrieves an entity instance using its id.
	 * 
	 * @param <T> Entity type.
	 * @param <E> Exception type.
	 * @param entityClass Entity class.
	 * @param id Id of the entity to retrieve.
	 * @param exception Exception class to be thrown if entity not found.
	 * @return Entity instance retrieved.
	 * @throws E Thrown if entity not found.
	 */
	public static <T, E extends Throwable> T byId(Class<T> entityClass, Object id, Class<E> exception) throws E {
		T entity = getJapaEngine().findById(entityClass, id);
		if (entity == null) {
			try {
				throw exception.newInstance();
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			} catch (InstantiationException e) {
				throw new RuntimeException(e);
			}
		}
		return entity;
	}

	/**
	 * Prepends and appends the '%' character to the specified value and returns the result.
	 * 
	 * @param value
	 * @return
	 */
	public static String forLike(String value) {
		return JpaUtils.forLike(value);
	}

	/**
	 * Prepends the '%' character to the specified value and returns the result.
	 * 
	 * @param value
	 * @return
	 */
	public static String forStartsWith(String value) {
		return JpaUtils.forStartsWith(value);
	}

	private static JapaEngine getJapaEngine() {
		JapaEngine engine = JapaEngine.LOCAL_JAPA_ENGINE.get();
		if (engine == null) {
			throw new IllegalStateException("Japa Engine not bound");
		}
		return engine;
	}
}
